package com.proton.carepatchtemp.database.daomanager;

import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.database.gen.DeviceDao;
import com.proton.carepatchtemp.database.table.Device;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * Created by MoonlightSW on 2017/2/21.
 */

public class DeviceManager {
    private DeviceDao mDeviceDao;

    public DeviceManager() {
        mDeviceDao = GreenDaoManager.get().getmDaoSession().getDeviceDao();
    }

    public static void deleteDevice(Long id) {
        getDeviceDao().deleteByKey(id);
    }

    public static Device getDevice(Long id) {
        return getDeviceDao().load(id);
    }

    public static List<Device> getMyDeviceByMac(String macAddress) {
        QueryBuilder queryBuilder = getDeviceDao().queryBuilder().where(DeviceDao.Properties.Btaddress.eq(macAddress), DeviceDao.Properties.Creator.eq(VCare.get().getUid()));
        return queryBuilder.list();
    }

    public static List<Device> getAll() {
        return getDeviceDao().loadAll();
    }

    public static void insertOrReplace(Device device) {
        getDeviceDao().insertOrReplace(device);
    }

    public static void update(Device device) {
        //update之后要清除缓存，否则获取的数据异常
        getDeviceDao().update(device);
        GreenDaoManager.get().getmDaoSession().clear();
    }

    public static void insertOrReplaceInTx(List<Device> devices) {
        getDeviceDao().insertOrReplaceInTx(devices);
    }

    private static DeviceDao getDeviceDao() {
        return GreenDaoManager.get().getmDaoSession().getDeviceDao();
    }
}
